<template>
  <view class="relative bg-white order-details">
    <nav-bar color="white" bg-color="black" title="订单详情" show-back></nav-bar>
    <u-row gutter="10rpx" customStyle="padding:10rpx;align-items:flex-start;">
      <u-col span="6">
        <text class="text-lg font-bold block my-5rpx">菜品信息</text>
        <text class="text-sm block my-5rpx text-slate-400">显示的单价为折扣后的价格</text>
        <view class="my-10rpx">
          <text class="text-base font-bold mr-10rpx"> 共{{ orderList.length }}个菜品</text>
          <text class="text-base font-bold"> 合计: ￥ {{ formatMoney(totalAmont) || "-" }} </text>
        </view>
        <uni-table :loading="pageStatus.loading" class="food-list" stripe emptyText="暂无更多数据" :border="true">
          <!-- 表头行 -->
          <uni-tr>
            <uni-th align="center" class="fixed-left">序号</uni-th>
            <uni-th align="center">菜品名称</uni-th>
            <uni-th align="left">备注</uni-th>
            <uni-th align="left">单价（元）</uni-th>
            <uni-th align="left">原价（元）</uni-th>
            <uni-th align="left">数量</uni-th>
            <uni-th align="left">合计（元）</uni-th>
            <uni-th align="left">退菜数</uni-th>
          </uni-tr>
          <!-- 表格数据行 -->
          <uni-tr v-for="(item, index) in orderList" :key="item.buffetOrderItemId">
            <uni-td align="center" class="fixed-left">{{ index + 1 }}</uni-td>
            <uni-td align="center">{{ item.foodName }}</uni-td>
            <uni-td align="center">{{ item.remark }}</uni-td>
            <uni-td align="center">{{ item.price || "" }}</uni-td>
            <uni-td align="center">{{ item.memberPrice || item.price || "-" }}</uni-td>
            <uni-td align="center">{{ item.foodNum }}</uni-td>
            <uni-td align="center">{{ item.foodNum * (item.memberPrice || item.price) }}</uni-td>
            <uni-td align="center">{{ item.refundQuantity || "0" }}</uni-td>
          </uni-tr>
        </uni-table>
      </u-col>
      <u-col span="6">
        <!-- 订单详情字段信息 -->
        <u-row gutter="10rpx" customStyle="padding:5rpx 10rpx;">
          <u-col span="6">
            <u-row gutter="10rpx">
              <u-col span="4" text-align="left"> <text class="details-text d-name">订单ID:</text> </u-col>
              <u-col span="8" text-align="right" class="details-text"> {{ details.buffetOrderId }}</u-col>
            </u-row>
          </u-col>
          <u-col span="6">
            <u-row gutter="5rpx">
              <u-col span="4" text-align="left"> <text class="details-text d-name">取餐号:</text> </u-col>
              <u-col span="8" text-align="right" class="details-text"> {{ details.mealNumber || "未出号" }}</u-col>
            </u-row>
          </u-col>
        </u-row>

        <u-row gutter="10rpx" customStyle="padding:5rpx 10rpx;">
          <u-col span="6">
            <u-row gutter="10rpx">
              <u-col span="4" text-align="left"> <text class="details-text d-name">下单时间:</text> </u-col>
              <u-col span="8" text-align="right" class="details-text"> {{ details.createTime }}</u-col>
            </u-row>
          </u-col>
          <u-col span="6">
            <u-row gutter="5rpx">
              <u-col span="4" text-align="left"> <text class="details-text d-name">订单人:</text> </u-col>
              <u-col span="8" text-align="right" class="details-text"> {{ details.customerInformationName }}</u-col>
            </u-row>
          </u-col>
        </u-row>

        <u-row gutter="10rpx" customStyle="padding:5rpx 10rpx;">
          <u-col span="6">
            <u-row gutter="10rpx">
              <u-col span="4" text-align="left"> <text class="details-text d-name">支付时间:</text> </u-col>
              <u-col span="8" text-align="right" class="details-text"> {{ details.payTime }}</u-col>
            </u-row>
          </u-col>
          <u-col span="6">
            <u-row gutter="5rpx">
              <u-col span="4" text-align="left"> <text class="details-text d-name">会员等级:</text> </u-col>
              <u-col span="8" text-align="right" class="details-text"> {{ details.membershipLevel || "-" }}</u-col>
            </u-row>
          </u-col>
        </u-row>

        <u-row gutter="10rpx" customStyle="padding:5rpx 10rpx;">
          <u-col span="6">
            <u-row gutter="10rpx">
              <u-col span="4" text-align="left"> <text class="details-text d-name">支付状态:</text> </u-col>
              <!-- 支付状态（0未支付 1已支付） -->
              <u-col span="8" text-align="right" class="details-text"> {{ payStatus[details.payStatus] || "-" }}</u-col>
            </u-row>
          </u-col>
          <u-col span="6"> </u-col>
        </u-row>

        <u-row customStyle="padding:0 20rpx;">
          <u-line margin="0.5em 0" />
        </u-row>

        <u-row gutter="10rpx" customStyle="padding:10rpx;">
          <view class="flex-col px-10rpx details-text">
            <!-- 是否堂食还是其他 -->
            <view class="py-5rpx">{{ diningStyles[details.diningStyle] || "-" }}</view>
            <view class="py-5rpx">下单人：{{ details.customerInformationName || "-" }}</view>
          </view>
        </u-row>

        <u-row customStyle="padding:0 20rpx;">
          <u-line margin="0.5em 0" />
        </u-row>

        <view>
          <text class="block p-10rpx px-20rpx text-base details-text d-name">支付信息</text>
        </view>

        <u-row gutter="10rpx" customStyle="padding:5rpx 10rpx;">
          <u-col span="6">
            <u-row gutter="10rpx">
              <u-col span="4" text-align="left"> <text class="details-text">订单金额:</text> </u-col>
              <u-col span="8" text-align="right" class="details-text"> ￥{{ formatMoney(details.money) || "-" }}</u-col>
            </u-row>
          </u-col>
          <u-col span="6">
            <u-row gutter="5rpx">
              <u-col span="4" text-align="left"> <text class="details-text">会员优惠:</text> </u-col>
              <u-col span="8" text-align="right" class="details-text d-price-discount">
                -￥{{ formatMoney(totalDiscount) || "0.00" }}</u-col
              >
            </u-row>
          </u-col>
        </u-row>

        <u-row gutter="10rpx" customStyle="padding:5rpx 10rpx;">
          <u-col span="6">
            <u-row gutter="10rpx">
              <u-col span="4" text-align="left"> <text class="details-text">退款金额:</text> </u-col>
              <u-col span="8" text-align="right" class="details-text text d-price-back">
                -￥{{ details.refundAmount || "0.00" }}</u-col
              >
            </u-row>
          </u-col>
          <u-col span="6">
            <u-row gutter="5rpx">
              <u-col span="4" text-align="left"> <text class="details-text">补贴金额:</text> </u-col>
              <u-col span="8" text-align="right" class="details-text">
                -￥{{ formatMoney(details.mealAllowance) }}</u-col
              >
            </u-row>
          </u-col>
        </u-row>

        <u-row gutter="10rpx" customStyle="padding:5rpx 10rpx;">
          <u-col span="6">
            <u-row gutter="10rpx">
              <u-col span="4" text-align="left"> <text class="details-text">支付方式:</text> </u-col>
              <u-col span="8" text-align="right" class="details-text">
                {{ getFieldValue("sys_payType", details.payType) || "-" }}</u-col
              >
            </u-row>
          </u-col>
        </u-row>

        <u-row gutter="10rpx" customStyle="padding:5rpx 10rpx;">
          <u-col span="6">
            <u-row gutter="10rpx">
              <u-col span="4" text-align="left"> <text class="details-text">支付合计:</text> </u-col>
              <u-col span="8" text-align="right" class="details-text d-price">
                ￥{{ formatMoney(details.amountcollected) }}</u-col
              >
            </u-row>
          </u-col>
        </u-row>

        <u-row customStyle="padding:0 20rpx;">
          <u-line margin="0.5em 0" />
        </u-row>

        <u-row gutter="10rpx" customStyle="padding:5rpx 10rpx;position:sticky;bottom:0;background-color:white">
          <u-col span="3">
            <u-button @click="printOrder" type="success" size="large" customStyle="font-weight:bold;"
              >打印小票</u-button
            >
          </u-col>

          <!-- refundStatus	退款状态(0未退款1已退款2部分退款) -->
          <template v-if="details.refundStatus != 1 && details.refundStatus != 2">
            <u-col span="3">
              <u-button
                :disabled="details.refundStatus == 2"
                type="error"
                size="large"
                customStyle="font-weight:bold;  border-top-right-radius: 0; border-bottom-right-radius: 0; margin-right: -20px;"
                @click="clickCancel"
                >退单</u-button
              >
            </u-col>
            <u-col span="3">
              <u-button
                type="warning"
                size="large"
                customStyle="font-weight:bold;  border-bottom-left-radius: 0; border-top-left-radius: 0;"
                @click="cancelDishes"
                >退菜</u-button
              >
            </u-col>
          </template>
          <template v-else>
            <text class="block ml-10rpx text-red-300"> 本订单已操作退款</text>
          </template>
        </u-row>
      </u-col>
    </u-row>

    <resultPopup ref="refCommonPopup" @confirm="popupConfirm" :show-icon="false">
      <template #default>
        <view class="my-30rpx flex-col items-center justify-center text-center">
          <text class="block font-bold text-red-500 text-oxl">￥{{ formatMoney(details.amountcollected) }} </text>
          <text class="block text-base py-10rpx text-gray-400"> 退款金额 </text>
        </view>
      </template>
      <template #confirm>
        <view class="btns flex">
          <view class="btns-item" @click="refCommonPopup.close(), (popupConfirmLoading = false)">
            <text class="btns-item-txt"> 取消 </text>
          </view>
          <view :class="['btns-item', 'confirm', popupConfirmLoading ? 'loading' : '']" @click="popupConfirm">
            <u-loading-icon mode="circle" :show="popupConfirmLoading" color="red" />
            <text class="btns-item-txt"> 确定 </text>
          </view>
        </view>
      </template>
    </resultPopup>

    <!-- 通知结果弹窗 -->
    <resultPopup ref="refResultPopup" :show-icon="true"></resultPopup>
  </view>
</template>
<script lang="ts" setup>
import { onLoad } from "@dcloudio/uni-app";
import { reactive, ref, onMounted, onBeforeUnmount, computed } from "vue";
import { getBuffetOrderDetail, netPrinterPrinting, onDemandRefund } from "@/api";
import { loadSysDict, getFieldValue, formatMoney } from "@/utils/util";
import resultPopup from "@/components/common-popup/result-popup.vue";
import { useStore } from "vuex";
import { printorder, printStart, printStartByDevice } from "@/pages/subReportForm/print-config/print-utils";

/**
 * orderStatus	订单状态（1未出单2已出单、未领 3已领餐、4已送达5逾期6退单7已评论8已派单9待派单10已取消）
 *
 * 订单状态 为 10 已取消 6退单 情况下， 不显示退单按钮
 */

const diningStyles = {
  1: "送餐",
  2: "堂食",
  3: "自提",
};

// 订单状态（1未出单2已出单、未领 3已领餐、4已送达5逾期6退单7已评论8已派单9待派单10已取消）
const orderStatus = {
  1: "未出单",
  2: "已出单",
  3: "已领餐",
  4: "已送达",
  5: "逾期",
  6: "退单",
  7: "已评论",
  8: "已派单",
  9: "待派单",
  10: "已取消",
};

const payStatus = {
  0: "未支付",
  1: "已支付",
};

const pageStatus = reactive({
  loading: false,
});

// 页面传递的参数
const pagePam = {
  id: "",
};

onLoad((e: any) => {
  console.log("onLoad:>", e);
  if (e.id) pagePam.id = e.id;
  loadSysDict(["sys_payType"]);
});

const orderList = ref([]);

const details = ref<any>({
  payType: "",
  refundStatus: 0,
});

const getPageData = async () => {
  console.log("getPageData:>", pagePam);
  pageStatus.loading = true;
  try {
    const pam = {
      buffetOrderId: pagePam.id,
    };
    const { data, success } = await getBuffetOrderDetail(pam);
    console.log(data);
    if (!success) throw new Error("获取数据失败");
    details.value = data;
    if (data.buffetOrderItemEntityList) {
      console.log("----- data.buffetOrderItemEntityList --", data.buffetOrderItemEntityList);
      orderList.value = data.buffetOrderItemEntityList;
    }
    pageStatus.loading = false;
  } catch (error) {
    pageStatus.loading = false;
    console.error(error);
  }
};

const refResultPopup = ref();
onMounted(async () => {
  getPageData();

  // 监听退款成功
  uni.$on("refund-success", ({ title, money, order }) => {
    // 刷新数据，并弹窗提示成功
    getPageData();

    refResultPopup.value.open({
      title,
      content: `退款成功，退款金额：￥${money}`,
      closeInAfter: 60000,
      autoClose: true,
    });
  });
});

onBeforeUnmount(() => {
  uni.$off("refund-success");
});

// 退单按钮点击
const clickCancel = () => {
  const popupConfig = {
    title: "订单退款",
    content: "",
    confirmText: "确认",
    cancelText: "取消",
    closeInAfter: 600000,
    autoClose: false,
  };
  refCommonPopup.value.open(popupConfig);
};

// 弹窗
const refCommonPopup = ref();

const popupConfirmLoading = ref(false);

// 退单确认
const popupConfirm = async () => {
  if (popupConfirmLoading.value) return;
  popupConfirmLoading.value = true;
  try {
    const pam = {
      /** 接口文档有点乱 */
      // ...details.value,
      // business,
      // businessId,
      // customerInformationId,
      // customerInformationName,
      // customerInformationPhone,
      // diningStyle,
      // mealtype,
      // ordernum,
      // orderStatus,
      // payType,
      ...details.value,
      //----------------------------------------------------
      // dataType: 3, //工单类型（1服务工单2商品订单3助餐订单4团购订单）
      orderId: details.value.buffetOrderId,
      // orderNum: ordernum,
      // problemDescription: "", // 	问题描述
      refundContent: "", // 退款原因
      refundImg: "", // 退款申请图片凭证
      refundNum: "", // 售后单号
      refundType: 1, // 退款类型（1仅退款2退货退款）
      itemList: orderList.value,
    };
    const { success } = await onDemandRefund(pam);
    if (success) {
      // 成功则返回并通知
      uni.$emit("refund-success", {
        // result: data
        title: "退款申请提交成功",
        money: details.value.amountcollected,
        order: details.value,
      });
    }
    popupConfirmLoading.value = false;
  } catch (error) {
    console.error(error);
    refResultPopup.value.open({
      title: "失败",
      content: error.data?.msg || "退款失败，请稍后重试",
      closeInAfter: 60000,
      autoClose: true,
      type: "fail",
    });
    popupConfirmLoading.value = false;
  }

  refCommonPopup.value.close();
};

// 退菜

const cancelDishes = () => {
  uni.navigateTo({
    url: "./order-cancel-dishes?id=" + pagePam.id,
  });
};

// 加算子表单的订单金额
const totalAmont = computed(() => {
  /** @item.memberPrice || item.price memberPrice 为会员价格  */
  return orderList.value.reduce((pre, cur) => {
    return pre + (cur.memberPrice || cur.price) * cur.foodNum;
  }, 0);
});

// 加算总的会员优惠
const totalDiscount = computed(() => {
  return orderList.value.reduce((pre, cur) => {
    let discount = cur.memberPrice ? (cur.price - cur.memberPrice) * cur.foodNum : 0;
    return pre + discount;
  }, 0);
});

const store = useStore();
// 打印小票(测试支付结束后的打印功能， 会根据前后台打印配置进行打印)
const printOrder = async () => {
  try {
    // 商家信息
    const { abbreviation } = store.getters.businessInfo;

    // 触发网络打印
    netPrinterPrinting(details.value.buffetOrderId).then(({success, data, msg}) => {
      if (!success) console.error("网络打印失败", {success, data, msg});
    }).catch((err) => {
      console.error("网络打印失败", err);
    });

    // 使用订单id 查询订单详细

    const orderDetails = details.value;
    const goodslist = orderDetails.buffetOrderItemEntityList.map((v) => {
      return {
        foodName: v.foodName,
        number: v.foodNum,
        price: formatMoney(/* v.memberPrice || */ v.price),
        totel: formatMoney(/* v.memberPrice ||  */ v.price * v.foodNum),
      };
    });

    const res = {
      orderNo: orderDetails.buffetOrderId,
      merchname: abbreviation,
      opuser: "默认收银员", // TODO 目前没有收银员登录账号，都是登录商家账号
      time: orderDetails.createTime,
      goodslist: goodslist,
      remark: getRemark(orderDetails.buffetOrderItemEntityList),
      fee: formatMoney(orderDetails.amountcollected),
      subsidies: formatMoney(orderDetails.mealAllowance),
      discount: formatMoney(totalDiscount.value),
      total: formatMoney(orderDetails.amountcollected),
    };

    // 直接根据前台打印配置打印
    // 将订单信息以固定参数格式处理，输出打印SDK可用的JSON数据
    const temp = store.getters.currentFrontTemplate;
    const printInstance = printorder(res, temp);
    // 查找一个前台类型的打印机进行输出
    const frontPrinter = store.getters.usbPrinterListFront;
    if (Array.isArray(frontPrinter) && frontPrinter.length > 0) {
      // 补打印小票只打印一台就行
      printStartByDevice(printInstance.data, frontPrinter[0].path);
    } else {
      // 打印
      await printStart(printInstance.data);
    }
  } catch (error: any) {
    console.error("toPrintTick 打印小票失败", error.message, error.stack);
  }
};

/** 循环购物车列表整合备注信息 */
const getRemark = (list: any) => {
  if (!Array.isArray(list) || list.length == 0) return "";
  return list
    .map((v) => {
      return `${v.foodName}: ${v.remark};`;
    })
    .join("\n");
};
</script>
<style lang="scss" scoped>
.order-details {
  .food-list {
    width: 100%;
    min-width: none !important;
  }

  ::v-deep .uni-table {
    min-width: auto !important;
  }

  .details-text {
    font-size: 10rpx;
    white-space: nowrap;
    overflow: scroll;

    &.d-name {
      color: rgb(179, 179, 179);
    }

    &.d-price {
      color: red;
      font-weight: bold;
    }

    &.d-price-back {
      color: rgb(14, 187, 52);
      font-weight: bold;
    }
    &.d-price-discount {
      color: orange;
      font-weight: bold;
    }
  }
}

.btns-item {
  background-color: #efefef;
  padding: 5rpx 20rpx;
  border-radius: 5rpx;
  margin: 0rpx 15rpx;
  font-size: 12rpx;
  &.confirm {
    color: white;
    background-color: red;
  }

  .btns-item-txt {
    font-size: 10rpx;
    padding: 5rpx 15rpx;
  }

  ::v-deep .u-button {
    padding: 2rpx 20rpx;
  }
}
/** 这是弹窗按钮的样式 */
@import "@/components/common-popup/btns.scss";
</style>
